package com.XDApp.xdbase.utils;

import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Display;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.SinaSsoHandler;

/**
 * @author rongfzh
 * 
 */
public class CommonUtil {
	final static UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.share", RequestType.SOCIAL);

	public static SharedPreferences getSharedPreferences(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				"xdsharepreferences", Context.MODE_PRIVATE);
		return sharedPreferences;
	}

	public static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			return false;
		}
		return true;
	}

	public static String getRootFilePath() {
		if (hasSDCard()) {
			return Environment.getExternalStorageDirectory().getAbsolutePath()
					+ "/";// filePath:/sdcard/
		} else {
			return Environment.getDataDirectory().getAbsolutePath() + "/data/"; // filePath:
																				// /data/data/
		}
	}

	public static boolean checkNetState(Context context) {
		boolean netstate = false;
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						netstate = true;
						break;
					}
				}
			}
		}
		return netstate;
	}

	public static void showToast(Context context, String tip) {
		// Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
	}

	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	public static boolean checkEmail(String email) {
		// 验证邮箱的正则表达式
		String format = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$";
		if (email.matches(format)) {
			return true;
			// 邮箱名合法，返回true
		} else {
			return false;
			// 邮箱名不合法，返回false
		}
	}

	public static boolean checkUser(String user) {
		String format = "^[a-zA-Z0-9\u4e00-\u9fa5]{3,}$";
		if (user.matches(format)) {
			return true;
			// 邮箱名合法，返回true
		} else {
			return false;
			// 邮箱名不合法，返回false
		}
	}

	public static boolean checkPassword(String password) {
		String format = "^[a-zA-Z0-9]{6,}$";
		if (password.matches(format)) {
			return true;
			// 邮箱名合法，返回true
		} else {
			return false;
			// 邮箱名不合法，返回false
		}
	}

	public static String getMD5(String string) {
		byte[] source = string.getBytes();
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };// 用来将字节转换成16进制表示的字符
		String s = null;
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2];// 每个字节用 16 进制表示的话，使用两个字符， 所以表示成 16
			// 进制需要 32 个字符
			int k = 0;// 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) {// 从第一个字节开始，对 MD5 的每一个字节// 转换成 16
				// 进制字符的转换
				byte byte0 = tmp[i];// 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
				// 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换
			}
			s = new String(str);// 换后的结果转换为字符串

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public static String getVersion(Context context) {
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(),
					0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getTheDateTime(String dateStr) {
		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DATE);
		int month = cal.get(Calendar.MONTH) + 1;
		int year = cal.get(Calendar.YEAR);
		/*
		 * System.out.println("year--" + year + "month---" + month + "day---" +
		 * day);
		 */
		String[] times = dateStr.split(" ");
		if (null == times || times.length == 0 || times.length != 2) {
			return null;
		}
		String yearDate = times[0];
		String time = times[1];
		String[] currentYear = yearDate.split("/");
		if (null == currentYear || currentYear.length == 0
				|| currentYear.length != 3) {
			return null;
		}
		String resolvYear = currentYear[0];
		String resolvMonth = currentYear[1];
		String resolvDay = currentYear[2];
		int intYear = Integer.parseInt(resolvYear);
		int intMonth = Integer.parseInt(resolvMonth);
		int intDay = Integer.parseInt(resolvDay);
		if (year == intYear && month == intMonth && day == intDay) {
			if (null != time && time.length() >= 5) {
				String temptimes[] = time.split(":");
				if (null != temptimes && temptimes.length != 3) {
					return time.substring(0, time.lastIndexOf(":"));
				}
				String hour = temptimes[0];
				String minute = temptimes[1];
				if (!TextUtils.isEmpty(hour) && hour.length() == 1) {
					hour = "0" + hour;
				}
				if (!TextUtils.isEmpty(minute) && minute.length() == 1) {
					minute = "0" + minute;
				}
				time = hour + ":" + minute;
			}
			return time;
		} else {
			if (null != yearDate && yearDate.length() > 5) {
				yearDate = yearDate.substring(5);
			}
			return yearDate;
		}
	}

	public static String getDateTime(String dateStr) {
		if (!TextUtils.isEmpty(dateStr)) {
			dateStr = dateStr.substring(0, 10);
		}
		return dateStr;
	}


	public static void shareSdk(Activity context, String content,
			String contentUrl) {
		String wxAppID = "";
		// 支持微信好友分享
		mController.getConfig().supportWXPlatform(context, wxAppID, contentUrl);
		// 支持微信朋友圈
		mController.getConfig().supportWXCirclePlatform(context, wxAppID,
				contentUrl);
		// 设置分享内容
		mController.setShareContent(content + contentUrl);
		// 设置新浪微博sso
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		mController.getConfig().setShareSms(true);
		// 分享的图片
		// mController.setShareMedia(new UMImage(this, R.drawable.icon));
		// 设置分享平台选择面板的平台显示顺序
		mController.getConfig().setPlatformOrder(SHARE_MEDIA.WEIXIN_CIRCLE,
				SHARE_MEDIA.WEIXIN, SHARE_MEDIA.SINA, SHARE_MEDIA.SMS);
		// 移除不需要的分析平台
		mController.getConfig().removePlatform(SHARE_MEDIA.RENREN,
				SHARE_MEDIA.DOUBAN, SHARE_MEDIA.QZONE, SHARE_MEDIA.EMAIL,
				SHARE_MEDIA.TENCENT,  SHARE_MEDIA.FACEBOOK);
//		SHARE_MEDIA.NULL,
		// 是否只有已登录用户才能打开分享选择页
		mController.openShare(context, false);
	}

	/**
	 * 转换文件大小
	 * 
	 * @param fileS
	 * @return B/KB/MB/GB
	 */
	public static String formatFileSize(long fileS) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 转换文件大小
	 * 
	 * @param fileS
	 * @return B/KB/MB/GB
	 */
	public static String formatFileSizeMB(long fileS) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("0.##");
		String fileSizeString = "";
		fileSizeString = df.format((double) fileS / 1048576) + "MB";
		return fileSizeString;
	}

	
}
